package stud.mpgame.old.game;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stud.mpgame.network.ISessionListener;
import stud.mpgame.network.NetworkMonitor;
import stud.mpgame.network.service.ping.PingService;
import stud.mpgame.old.ServerConfiguration;
import stud.mpgame.snapshot.SnapshotManager;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class GameProtocolHandler implements ISessionListener {

    private final static Logger LOGGER = LoggerFactory.getLogger(GameProtocolHandler.class);

    public static final boolean PING_SERVICE_NOTIFY_CLIENT = false;

    private final Set<IoSession> sessions = Collections
            .synchronizedSet(new HashSet< IoSession >());

    private NetworkMonitor networkMonitor;
    private PingService pingService;
    private SnapshotManager snapshotManager;

    public GameProtocolHandler(NetworkMonitor networkMonitor, SnapshotManager snapshotManager) {
        this.networkMonitor = networkMonitor;
        int pingServiceTickTime = ServerConfiguration.getInstance().getPingDelay();
        this.pingService = new PingService(networkMonitor, pingServiceTickTime, PING_SERVICE_NOTIFY_CLIENT);
        this.snapshotManager = snapshotManager;
        networkMonitor.addSessionListener(this);
    }

    public Set<IoSession> getSessions() {
        return sessions;
    }

    public void sessionOpened(IoSession session) {
        sessions.add(session);
        snapshotManager.addCommand(new PlayerAddCommand(networkMonitor.nowTime(), session));
        Player.increaseLastID();
        pingService.addSession(session);
    }

    public void sessionClosed(IoSession session) {
        snapshotManager.addCommand(new PlayerRemoveCommand(networkMonitor.nowTime(), session));
        pingService.removeSession(session);
        sessions.remove(session);
    }

}